const { Service } = require('egg')
const cheerio = require('cheerio')
const fs = require('fs')
const { pinyin } = require('pinyin-pro')
const { tableToList } = require('../utils/tools')

module.exports = class TreeService extends Service {
  /**
   * * 班级
   * @return {object} *
   */
  async class_() {
    const Cookie = this.ctx.state.Cookie
    const { term } = this.ctx.data
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_xzb`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 20000,
    })
    const tree = {
      [term]: [],
    }

    if (res.status === 200) {
      const $ = cheerio.load(res.data.toString())
      try {
        /* 根据学期构造年级 (4个) */
        const njList = []
        for (let i = 0; i < 4; i++) {
          const value = `${Number(term.split('-')[0] - i)}`
          njList.push({
            value,
            label: value,
            children: [],
          })
        }
        // console.log('njList', njList);

        /* 获取院系 */
        const yxList = []
        tree[term] = yxList
        $('#skyx').find('option').each((_, e) => {
          const value = e.attribs.value
          const name = $(e).text().replace(/\s/g, '').split(']')[1]
          if (value && name.includes('学院')) {
            yxList.push({
              value,
              label: name,
              children: JSON.parse(JSON.stringify(njList)),
            })
          }
        })
        yxList.sort((a, b) => a.label.length - b.label.length)
        // console.log('yxList', yxList);

        /* 获取专业 */
        const zyP = []
        for (const i of yxList) { // 构造请求
          const yx = i.value // 院系id
          for (const j of i.children) {
            const nj = j.value // 年级
            const query = this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/kbcx/getZyByAjax?&skyx=${yx}&sknj=${nj}`, {
              method: 'GET',
              headers: {
                Cookie,
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
              },
              timeout: 20000,
            })
            zyP.push(query)
          }
        }
        let index = 0
        const resAll = await Promise.all(zyP) // 请求
        for (let i = 0; i < yxList.length; i++) { // 合并数据
          for (let j = 0; j < yxList[i].children.length; j++) {
            const resZY = resAll[index++]
            const zyList = JSON.parse(resZY.data.toString()).map((e) => ({
              value: e.dm,
              label: e.dmmc,
              children: [],
            }))
            zyList.sort((a, b) => a.label.length - b.label.length)
            yxList[i].children[j].children = zyList
          }
        }

        /* 获取班级 */
        const bjP = []
        for (const i of yxList) { // 构造请求
          const yx = i.value // 院系id
          for (const j of i.children) {
            const nj = j.value // 年级
            for (const k of j.children) {
              const zy = k.value // 专业id
              const query = this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_xzb_ifr`, {
                method: 'POST',
                headers: {
                  Cookie,
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
                },
                data: {
                  xnxqh: term,
                  skyx: yx,
                  sknj: nj,
                  skzy: zy,
                  zc1: '',
                  zc2: '',
                  jc1: '',
                  jc2: '',
                },
                timeout: 20000,
              })
              bjP.push(query)
            }
          }
        }
        index = 0
        const resAll2 = await Promise.all(bjP) // 请求
        for (let i = 0; i < yxList.length; i++) { // 合并数据
          for (let j = 0; j < yxList[i].children.length; j++) {
            for (let k = 0; k < yxList[i].children[j].children.length; k++) {
              const resBJ = resAll2[index++]
              const bjList = tableToList(resBJ.data.toString(), '#kbtable').slice(2).map((e) => ({
                value: e[0],
                label: e[0],
              }))
              yxList[i].children[j].children[k].children = bjList
            }
          }
        }

        /* 储存 */
        const filePath = './app/public/tree-class.json'
        // 判断文件是否存在
        fs.promises.access(filePath, fs.constants.F_OK)
          .then(() => fs.promises.readFile(filePath, 'utf-8')) // 文件存在，读取文件内容
          .then((data) => {
            const jsonData = JSON.parse(data) // 文件内容转为对象
            jsonData[term] = yxList
            fs.writeFileSync(filePath, JSON.stringify(jsonData))
          })
          .catch((err) => {
            if (err.code === 'ENOENT') {
              fs.writeFileSync(filePath, JSON.stringify(tree))
            } else {
              console.error('读取文件出错', err)
            }
          })

        return tree
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return tree
  }

  /**
   * * 教师  学期 —— 学院 —— 教师
   * @return {object} *
   */
  async teacher() {
    const Cookie = this.ctx.state.Cookie
    const { term } = this.ctx.data
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_teacher`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 20000,
    })
    const tree = {
      [term]: [],
    }

    if (res.status === 200) {
      const $ = cheerio.load(res.data.toString())
      try {
        /* 获取院系 */
        const yxList = []
        tree[term] = yxList
        $('#skyx').find('option').each((_, e) => {
          const value = e.attribs.value
          const name = $(e).text().replace(/\s/g, '').split(']')[1]
          if (value && name.includes('学院')) {
            yxList.push({
              value,
              label: name,
              children: [],
            })
          }
        })
        yxList.sort((a, b) => a.label.length - b.label.length)
        // console.log('yxList', JSON.stringify(yxList, null, 2));

        /* 获取教师 */
        const jsP = []
        for (const i of yxList) { // 构造请求
          const yx = i.value // 院系id
          const query = this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_teacher_ifr`, {
            method: 'POST',
            headers: {
              Cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
            },
            timeout: 20000,
            data: {
              xnxqh: term,
              skyx: yx,
              jszc: '',
              teacherID: '',
              jg0101id: '',
              jg0101mc: '',
              zc1: '',
              zc2: '',
              jc1: '',
              jc2: '',
            },
          })
          jsP.push(query)
        }
        const resAll = await Promise.all(jsP) // 请求
        for (let i = 0; i < yxList.length; i++) { // 合并数据
          const resJS = resAll[i]
          const jsList = tableToList(resJS.data.toString(), '#kbtable').map((e) => {
            const text = e[0]
            const pinyinResult = pinyin(text, { toneType: 'none' })
            return {
              value: pinyinResult,
              label: text,
            }
          }).slice(2) // 删除前两个
            .sort((a, b) => a.value.localeCompare(b.value)) // 首字母排序
          yxList[i].children = jsList
        }

        /* 储存 */
        const filePath = './app/public/tree-teacher.json'
        // 判断文件是否存在
        fs.promises.access(filePath, fs.constants.F_OK)
          .then(() => fs.promises.readFile(filePath, 'utf-8')) // 文件存在，读取文件内容
          .then((data) => {
            const jsonData = JSON.parse(data) // 文件内容转为对象
            jsonData[term] = yxList
            fs.writeFileSync(filePath, JSON.stringify(jsonData))
          })
          .catch((err) => {
            if (err.code === 'ENOENT') {
              fs.writeFileSync(filePath, JSON.stringify(tree))
            } else {
              console.error('读取文件出错', err)
            }
          })

        return tree
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return tree
  }

  /**
   * * 教室 学期 —— 校区 —— 教学楼 —— 教室
   * @return {object} *
   */
  async classroom() {
    const Cookie = this.ctx.state.Cookie
    const { term } = this.ctx.data
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_classroom`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 20000,
    })
    const tree = {
      [term]: [],
    }

    if (res.status === 200) {
      const $ = cheerio.load(res.data.toString())
      try {
        /* 获取校区 */
        const xqList = []
        tree[term] = xqList
        $('#xqid').find('option').each((_, e) => {
          const value = e.attribs.value
          const name = $(e).text().replace(/\s/g, '')
          if (value) {
            xqList.push({
              value,
              label: name,
              children: [],
            })
          }
        })
        xqList.sort((a, b) => a.label.length - b.label.length)
        // console.log('xqList', JSON.stringify(xqList, null, 2));

        /* 获取教学楼 */
        const jxlP = []
        for (const i of xqList) { // 构造请求
          const xq = i.value // 校区id
          const query = this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/kbcx/getJxlByAjax`, {
            method: 'POST',
            headers: {
              Cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
            },
            data: {
              xqid: xq,
            },
            timeout: 20000,
          })
          jxlP.push(query)
        }

        const resAll1 = await Promise.all(jxlP) // 请求
        for (let i = 0; i < xqList.length; i++) { // 合并数据
          const resJXL = resAll1[i]
          const jxlList = JSON.parse(resJXL.data.toString()).map((e) => ({
            value: e.dm,
            label: e.dmmc,
            children: [],
          }))
          jxlList.sort((a, b) => a.label.length - b.label.length)
          xqList[i].children = jxlList
        }

        /* 获取教室 */
        const jsP = []
        for (const i of xqList) { // 构造请求
          const xq = i.value // 校区id
          for (const j of i.children) {
            const jxl = j.value
            const query = this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_classroom_ifr`, {
              method: 'POST',
              headers: {
                Cookie,
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
              },
              timeout: 20000,
              data: {
                xnxqh: term,
                skyx: '',
                xqid: xq,
                jzwid: jxl,
                classroomID: '',
                jx0601id: '',
                jx0601mc: '',
                zc1: '1',
                zc2: '3',
                jc1: '',
                jc2: '',
              },
            })
            jsP.push(query)
          }
        }
        let index = 0
        const resAll2 = await Promise.all(jsP) // 请求
        for (let i = 0; i < xqList.length; i++) { // 合并数据
          for (let j = 0; j < xqList[i].children.length; j++) {
            const resJS = resAll2[index++]
            const jsList = tableToList(resJS.data.toString(), '#kbtable').map((e) => ({
              value: e[0],
              label: e[0],
            })).slice(2) // 删除前两个
            xqList[i].children[j].children = jsList
          }
        }

        /* 储存 */
        const filePath = './app/public/tree-classroom.json'
        // 判断文件是否存在
        fs.promises.access(filePath, fs.constants.F_OK)
          .then(() => fs.promises.readFile(filePath, 'utf-8'))// 文件存在，读取文件内容
          .then((data) => {
            const jsonData = JSON.parse(data) // 文件内容转为对象
            jsonData[term] = xqList
            fs.writeFileSync(filePath, JSON.stringify(jsonData))
          })
          .catch((err) => {
            if (err.code === 'ENOENT') {
              fs.writeFileSync(filePath, JSON.stringify(tree))
            } else {
              console.error('读取文件出错', err)
            }
          })

        return tree
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return tree
  }
}
